// 导入默认图片
import defalutImg from '@/assets/images/200.png'

export default {
  install (app) {
    defineDirective(app)
  }
}

// 指令
const defineDirective = (app) => {
  // 图片懒加载指令
  app.directive('lazy', {
    mounted (el, binding) {
      const observe = new IntersectionObserver(([{ isIntersecting }]) => {
        // 如果进入可视区域
        if (isIntersecting) {
          // 停止观察
          observe.unobserve(el)
          el.onerror = () => {
            // 设置请求错误时的默认图片
            el.src = defalutImg
          }
          el.src = binding.value
        }
      }, {
        threshold: 0.01
      })
      // 观察
      observe.observe(el)
    }
  })
}
